<?php
/**
 * Created by PhpStorm.
 * User: fengdh
 * Date: 2019/8/20
 * Time: 17:26
 */

namespace search\models;

use business\base\services\DictionaryService;
use business\elasticsearch\models\DeveloperModel;

class DeveloperSearchForm extends BaseSearchForm
{
    /**
     * @var int 公司等级筛选
     */
    public $developerType;

    /**
     * @var int 最后活动时间筛选
     */
    public $activitySort;

    /**
     * @var int 需求数量排序
     */
    public $procurementSort;

    /**
     * @var int 是否上市公司（0：否 1：是）
     */
    public $isIPO;

    /**
     * @var string 企业性质（1：国企 2：国有控股 3：央企）
     */
    public $enterpriseNature;

    public $area;

    public function rules()
    {
        return [
            [array_keys($this->getAttributes()), 'safe'],
        ];
    }

    public function search()
    {
        $condition = $this->constructCondition();
        $query = DeveloperModel::find()->query($condition);
        //高亮处理
        $highlight = [
            'pre_tags' => ['<em class="_high">'],
            'post_tags' => ['</em>'],
            "fields"=>[
                "developerName" => new \stdClass(),
            ]
        ];
        $query->highlight($highlight);

        $query->orderBy(['_score' => SORT_DESC, 'lastActivityTime' => SORT_DESC]);

        $total = $query->count();

        //分页处理
        $query->offset(($this->page - 1) * $this->pageSize)->limit($this->pageSize);

        $data = $query->asArray()->all();

        //数据处理
        $result = ['resultNum' => $total, 'resultSet' => []];
        foreach ($data as $dv) {
            $tmp = $dv['_source'];
            $tmp['nameSuggest'] = $tmp['developerName'];
            if (!empty($dv['highlight'])) {
                foreach ($dv['highlight'] as $key => $value) {
                    $tmp[$key . 'HL'] = isset($value[0]) ? $value[0] : '';
                }
            }
            $result['resultSet'][] = $tmp;
        }

        //添加搜索记录
        if ((int)$this->page === 1) {
            $this->addSearchRecord($this->keyword, $this->keyword, $total, "developer", $this->portal);
        }

        return $result;
    }

    public function searchByDeveloperId($developerId){
        $condition =[
            "match"=>[
                "developerId.keyword"=>$developerId
            ]
        ];
        $query = DeveloperModel::find()->query($condition);
        $data = $query->asArray()->one();
        return $data;
    }

    private function constructCondition()
    {
        $query = [];
        if (isset($this->developerType) && $this->developerType !== '') {
            $developerType = [];
            if ($this->developerType == 0) {
                //$developerType = ['普通', '500强'];
                $developerType = ["普通", "500强"];
            } elseif ($this->developerType == 100) {
                //$developerType = ['100强'];
                $developerType = ["100强"];
            } elseif ($this->developerType == 500) {
                $developerType = ['100强', '500强'];
            }
            if (!empty($developerType)) {
                $query['function_score']['query']['bool']['filter'][] = DeveloperModel::developerType($developerType);
            }
        }

        if (!empty($this->area)) {
            $registerLocationCode = $serviceArea = explode(',', $this->area);
            $dictionaryService = new DictionaryService();
            $region = $dictionaryService->getRegionHierarchyByCode($serviceArea);
            if (!empty($region) && !empty($region->childRegionNodes)) {
                foreach ($region->childRegionNodes as $childRegion) {
                    $registerLocationCode[] = $childRegion->code;
                }
            }
            $query['function_score']['query']['bool']['filter'][] = DeveloperModel::regCityCode($registerLocationCode);
        }

        if ($this->isIPO == 1) {
            $query['function_score']['query']['bool']['filter'][] = [
                'term' => [
                    'isIPO' => $this->isIPO
                ]
            ];
        }

        if ($this->enterpriseNature) {
            $enterpriseNatureArr = explode(',', $this->enterpriseNature);
            if (count($enterpriseNatureArr) == 1){
                $query['function_score']['query']['bool']['filter'][] = [
                    'term' => [
                        'enterpriseNature' => $this->enterpriseNature
                    ]
                ];
            } else {
                $query['function_score']['query']['bool']['filter'][] = [
                    'terms' => [
                        'enterpriseNature' => $enterpriseNatureArr
                    ]
                ];
            }

        }

        if (!empty($this->keyword)) {
            $query['function_score']['query']['bool']['should'] = [
                //['match' => ['shortName' => ['query' => $this->keyword]]],
                ['match' => ['developerName' => ['query' => $this->keyword, 'analyzer'=>'ik_smart']]],
                ['match_phrase' => ['developerName' => ['query' => $this->keyword, 'boost' => 50,'slop' => 2]]],
            ];
        }
        if (!empty($query['function_score']['query']['bool']['should'])) {
            $query['function_score']['query']['bool']['minimum_should_match'] = 1;
        }

        return $query;
    }

}